package tomcat.ch01;

import javax.imageio.stream.FileImageInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Response {

    /*
        HTTP Response = Status-Line
        *(( general-header | response-header | entity-header ) CRLF)
        CRLF
        [ message-body ]
        Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
     */


    private static final int BUFFER_SIZE = 1024;
    Request request;
    OutputStream output;

    public Response(OutputStream output) {
        this.output = output;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    public void sendStaticResource() throws IOException {
        byte[] bytes = new byte[BUFFER_SIZE];
        FileInputStream fis = null;
        try{
            File file = new File(HttpServer.WEB_ROOT, request.getUri());
            if(file.exists()){
                // ERR_INVALID_HTTP_RESPONSE
                // chrome : localhost 发送的响应无效。

                // my add
//                StringBuilder respHead = new StringBuilder();
//                respHead.append("HTTP/1.1 200 OK\r\n");
//                respHead.append("Content-Type: text/html\r\n");
//                respHead.append("Content-Length: 2300\r\n");
//                respHead.append("\r\n");
//                output.write(respHead.toString().getBytes());


                fis = new FileInputStream(file);
                int ch = fis.read(bytes, 0, BUFFER_SIZE);
                while (ch != -1){
                    output.write(bytes, 0, ch);
                    ch = fis.read(bytes, 0, BUFFER_SIZE);
                }
            }else {
                // file not found
                StringBuilder sbb = new StringBuilder();
                sbb.append("HTTP/1.1 404 File Not Found\r\n");
                sbb.append("Content-Type: text/html\r\n");
                sbb.append("Content-Length: 23\r\n");
                sbb.append("\r\n");
                sbb.append("<h1>File Not Found</h1>");

                output.write(sbb.toString().getBytes());
            }
        }catch (Exception e){
            // thrown if cannot instantiate a File object
            System.out.println(e.toString());
        }finally {
            if(fis != null){
                fis.close();
            }
        }
    }
}
